package com.polaris.live.ui.backpack.fragment

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.polaris.live.R.drawable
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentMainBackpackBinding
import com.polaris.live.dialog_fragment.room_background.fragment.RoomBackgroundFragment
import com.polaris.live.interface_bag.BackPackNumberCallback
import com.polaris.live.interface_bag.BackPackSelectCallback
import com.polaris.live.interface_bag.BackPackToolCallback
import com.polaris.live.popup.GiftRecordPopup
import com.polaris.live.popup.PreviewCommodityPopup
import com.polaris.live.resp.back_resp.UserBackpackConsumableResp
import com.polaris.live.resp.back_resp.UserBackpackDecorationResp
import com.polaris.live.resp.back_resp.UserBackpackNumberResp
import com.polaris.live.resp.back_resp.UserBackpackResp
import com.polaris.live.translation.R
import com.polaris.live.utils.AppConfigUtils
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.backpack.BackPackMainModel
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil.loadPag
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.libpag.PAGFile

/**
 * 背包主页
 *
 * @author Created by 天晴 on 2024/7/16 15:46
 * @since 1.0.0
 **/
class BackpackMainFragment : BaseVbFragment<BackPackMainModel, FragmentMainBackpackBinding>(),
    BackPackSelectCallback, BackPackToolCallback, BackPackNumberCallback {

    private val decorationType by lazy { arguments?.getLong("decorationType", -1) ?: -1 }

    private val mObjectType by lazy { arguments?.getInt("objectType") }

    private val mList = ArrayList<Long>()

    private val mFragments = ArrayList<Fragment>()

    private val mTitles = ArrayList<TabBean>()

    private var mOnBackPackSelectCallback: BackPackSelectCallback? = null

    private val mDecorationNames by lazy {
        AppConfigUtils.getDecorationNames()
    }

    private val mBubbleFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.CHAT_BUBBLE
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mAvatarFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.AVATAR_FRAME
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mScreenFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.LIVE_BROADCAST_ENTRY
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mProfileFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.USER_PROFILE
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mLiveEffectFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.LIVE_EFFECT
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mHomePageBackgroundFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.HOMEPAGE_BACKGROUND
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mPartyBackgroundFragment by lazy {
        RoomBackgroundFragment().apply {
            arguments = bundleOf(
                "isPopup" to false
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }

    /**
     * 声浪
     */
    private val mPartySoundEffectFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.SOUND_EFFECT
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }

    /**
     * 房間框
     */
    private val mRoomFrameFragment by lazy {
        BackpackFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.ROOM_FRAME
            )
            setOnBackPackSelectCallback(this@BackpackMainFragment)
        }
    }
    private val mToolFragment by lazy {
        BackpackToolFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.TOOL
            )
            setBackPackToolCallback(this@BackpackMainFragment)
        }
    }
    private val mBackpackNumberFragment by lazy {
        BackpackNumberFragment().apply {
            arguments = bundleOf(
                "type" to CommonConst.DressUp.BEAUTIFUL_NUMBER
            )
            setBackPackNumberCallback(this@BackpackMainFragment)
        }
    }

    private var timeJob: Job? = null
    private fun startTime() {
        cancelTime()
        timeJob = mViewModel.viewModelScope.launch {
            while (isActive) {
                delay(1000)
                when (val fr = mFragments.getOrNull(mBinding.inContent.viewpager2.currentItem)) {
                    is BackpackFragment -> {
                        fr.timerUpdate()
                    }

                    is BackpackToolFragment -> {
                        fr.timerUpdate()
                    }

                    is BackpackNumberFragment -> {
                        fr.timerUpdate()
                    }
                }

            }
        }
    }

    private fun cancelTime() {
        timeJob?.cancel()
        timeJob = null
    }

    //上次点击的item
    private var mLastItem: UserBackpackDecorationResp? = null

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.framePag.setRepeatCount(-1)
        mBinding.screenPag.setRepeatCount(-1)
        mBinding.profilePag.setRepeatCount(-1)

        initObserver()

        if (resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL) {
            mBinding.detailsTv.setBackgroundResource(drawable.r24_back_ffffff_trbr)
        }

        mBinding.detailsTv.setOnSingleClickListener {
            mLastItem?.let {
                GiftRecordPopup.show(requireContext(), mViewModel, it.backpackId.toInt())
            }
        }

        mBinding.previewLl.setOnSingleClickListener {
            mLastItem?.let { resp ->
                val url = when (resp.decorationType) {
                    CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                        resp.ext
                    }

                    CommonConst.DressUp.SOUND_EFFECT -> {
                        resp.ext
                    }

                    CommonConst.DressUp.ROOM_FRAME -> {
                        resp.ext
                    }

                    else -> {
                        resp.effectDisplayUrl
                    }
                }
                PreviewCommodityPopup.show(requireContext(), resp.decorationType, url ?: resp.displayUrl)
            }

        }
    }

    override fun initData() {
        super.initData()
        mViewModel.getBackpack()

        startTime()
    }

    private fun initTitle() {
        mBinding.inContent.viewpager2.adapter = ViewPagerAdapter(mFragments, this)

        mBinding.inContent.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.inContent.viewpager2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        mBinding.inContent.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mBinding.inContent.tab.setRed(position, false)

            }
        })
        mBinding.inContent.tab.setViewPage(mBinding.inContent.viewpager2)
        mBinding.inContent.tab.setTabs(mTitles, mBinding.inContent.svScroll)
        if (decorationType != -1L) {
            goBackpack(decorationType, mObjectType)
        } else {
            mBinding.inContent.viewpager2.currentItem = 0
        }
    }

    /**
     * 对比查找设置
     */
    private inline fun <reified T> List<Fragment>.highlightTabFor(condition: (T) -> Boolean = { true }) {
        val index = indexOfFirst { it is T && condition(it as T) }
        if (index != -1 && index != mBinding.inContent.viewpager2.currentItem) {
            mBinding.inContent.tab.setRed(index, true)
        }
    }

    private fun initObserver() {
        mViewModel.mBackpackNewAllLiveData.observe(this) { resultState ->
            parseState(resultState, { resultData ->
                if (resultData.consumableNew) {
                    mFragments.highlightTabFor<BackpackToolFragment>()
                }
                resultData.decorationNews?.forEach { da ->
                    mFragments.highlightTabFor<BackpackFragment> { fragment ->
                        fragment.getType().toString() == da.key
                    }
                }
            })
        }
        mViewModel.mBackpackLiveData.observe(this) { resultState ->
            parseState(resultState, { resp ->
                resp.consumables?.also { resultData ->
                    if (resultData.isNotEmpty()) {
                        mTitles.add(
                            TabBean(
                                mDecorationNames?.get("${CommonConst.DressUp.TOOL}")
                                    ?: StringUtils.getString(R.string.shopping_tool)
                            )
                        )
                        mFragments.add(mToolFragment)
                        mList.add(CommonConst.DressUp.TOOL)
                        (mToolFragment as? BackpackToolFragment)?.onBackPackDataCallback(resultData)
                    }
                }
                resp.numbers?.also { resultData ->
                    if (resultData.isNotEmpty()) {
                        mTitles.add(
                            TabBean(
                                mDecorationNames?.get("${CommonConst.DressUp.BEAUTIFUL_NUMBER}")
                                    ?: StringUtils.getString(R.string.beautiful_number)
                            )
                        )
                        mFragments.add(mBackpackNumberFragment)
                        mList.add(CommonConst.DressUp.BEAUTIFUL_NUMBER)
                        (mBackpackNumberFragment as? BackpackNumberFragment)?.onBackPackDataCallback(resultData)
                    }
                }

                resp.backpack?.also {
                    handleBackpackData(it)
                }

                mBinding.inContent.viewpager2.offscreenPageLimit = mFragments.size
                if (mFragments.isEmpty()) {
                    return@parseState
                }

                initTitle()

                mViewModel.getBackpackNewAll()
            })
        }
        mViewModel.mDiyAndBackLiveData.observe(this) { resp ->
            val diyResp = resp.first
            val backpackResp = resp.second
            val item = diyResp?.list?.find { it.useStatus.toBoolean() }
            //判断自定义背景是否有使用的，如果没有则有效背景来处理默认选中的问题
            if (item == null) {
                mPartyBackgroundFragment.setonBackPackData(backpackResp)
            } else {
                mPartyBackgroundFragment.setonBackPackData(backpackResp, false)
            }
        }
    }

    private fun handleBackpackData(resultData: UserBackpackResp) {
        resultData.map.forEach {
            when (it.key.toLong()) {
                CommonConst.DressUp.CHAT_BUBBLE -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.CHAT_BUBBLE}")
                            ?: StringUtils.getString(R.string.shopping_bubble),
                        mBubbleFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.AVATAR_FRAME -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.AVATAR_FRAME}")
                            ?: StringUtils.getString(R.string.shopping_avatar),
                        mAvatarFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.LIVE_BROADCAST_ENTRY}")
                            ?: StringUtils.getString(R.string.shopping_car),
                        mScreenFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.USER_PROFILE -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.USER_PROFILE}")
                            ?: StringUtils.getString(R.string.shopping_info_card),
                        mProfileFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.LIVE_EFFECT -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.LIVE_EFFECT}")
                            ?: StringUtils.getString(R.string.shopping_entrance),
                        mLiveEffectFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.HOMEPAGE_BACKGROUND -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.HOMEPAGE_BACKGROUND}")
                            ?: StringUtils.getString(R.string.shopping_floating),
                        mHomePageBackgroundFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.PARTY_BACKGROUND -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.PARTY_BACKGROUND}")
                            ?: StringUtils.getString(R.string.shopping_background),
                        mPartyBackgroundFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.SOUND_EFFECT -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.SOUND_EFFECT}")
                            ?: StringUtils.getString(R.string.voice_sound),
                        mPartySoundEffectFragment,
                        it.value
                    )
                }

                CommonConst.DressUp.ROOM_FRAME -> {
                    addTabAndCallback(
                        it.key.toLong(),
                        mDecorationNames?.get("${CommonConst.DressUp.ROOM_FRAME}")
                            ?: StringUtils.getString(R.string.room_frame),
                        mRoomFrameFragment,
                        it.value
                    )
                }

            }
        }
    }

    /**
     * 更新数据
     */
    fun updateData(type: Long) {
        mFragments.forEach {
            if (it is BackpackFragment) {
                it.updateData(type)
            }
            if (it is BackpackNumberFragment) {
                it.updateData(type)
            }
            if (it is BackpackToolFragment) {
                it.updateData()
            }
        }
        mViewModel.getBackpackNewAll()
    }

    fun goIndex(type: Long) {
        val index = mList.indexOfFirst { it == type }
        if (index == -1) {
            return
        }
        mBinding.inContent.viewpager2.currentItem = index
        mBinding.inContent.tab.onPageSelected(index)
    }

    //添加fragment和数据
    private fun addTabAndCallback(
        type: Long,
        title: String,
        fragment: Fragment,
        data: List<UserBackpackDecorationResp>,
    ) {
        mTitles.add(TabBean(title))
        mFragments.add(fragment)
        mList.add(type)
        (fragment as? BackpackFragment)?.onBackPackDataCallback(data)
        if (type == CommonConst.DressUp.PARTY_BACKGROUND) {
            mViewModel.getDiyBackpack(data)
        }
    }

    //预览回调
    override fun onBackPackSelectCallback(item: UserBackpackDecorationResp?) {
        mBinding.cosHead.visibility = View.GONE
        mBinding.avFv.visibility = View.GONE
        mBinding.cosProfile.visibility = View.GONE
        mBinding.chatIcon.visibility = View.GONE
        mBinding.cosScreen.visibility = View.GONE
        mBinding.frameAvatar.visibility = View.GONE
        mBinding.framePag.visibility = View.GONE
        mBinding.frameBack.visibility = View.GONE
        mBinding.screenPag.visibility = View.GONE
        mBinding.screenBack.visibility = View.GONE
        mBinding.effectIcon.visibility = View.GONE
        mBinding.profilePag.visibility = View.GONE
        mBinding.profileBack.visibility = View.GONE
        mBinding.previewLl.visibility = View.GONE
        mBinding.entryScreenItemview.visibility = View.GONE
        if (item == null) {
            return
        }
        mLastItem = item
        when (item.decorationType) {
            CommonConst.DressUp.AVATAR_FRAME -> {
                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.contains(".pag?")) {
                    mBinding.avFv.visibility = View.VISIBLE
                    mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(item.effectDisplayUrl))
                    mBinding.avHead.setImageUrl(UserManager.getUser().avatar)
                } else if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    mBinding.framePag.composition = PAGFile.Load("")
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showFramePag(item)
                        }
                    }

                } else {
                    showFrameImage(item)
                }

            }

            CommonConst.DressUp.USER_PROFILE -> {
                mBinding.profileAvatar.setImageUrl(UserManager.getUser().avatar)
                mBinding.cosProfile.visibility = View.VISIBLE
                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, localPath ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            mBinding.profilePag.visibility = View.VISIBLE
                            mBinding.profilePag.apply {
                                composition = PAGFile.Load(localPath)
                                if (!isPlaying) {
                                    play()
                                }
                            }
                        }
                    }
                } else {
                    mBinding.profileBack.visibility = View.VISIBLE
                    Glide.with(mBinding.profileBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                        .into(mBinding.profileBack)
                }
            }

            CommonConst.DressUp.CHAT_BUBBLE -> {
                mBinding.chatIcon.visibility = View.VISIBLE
                Glide.with(mBinding.chatIcon).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                    .into(mBinding.chatIcon)
            }

            CommonConst.DressUp.LIVE_EFFECT -> {
                mBinding.previewLl.visibility = View.VISIBLE
                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            mBinding.entryScreenItemview.visibility = View.VISIBLE
                            mBinding.entryScreenItemview.setData(item.effectDisplayUrl)
                        }
                    }
                } else {
                    mBinding.entryScreenItemview.visibility = View.VISIBLE
                    mBinding.entryScreenItemview.setData(item.effectDisplayUrl ?: item.displayUrl)
                }
            }

            CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenPag.composition = PAGFile.Load("")

                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showScreenPag(effectDisplayUrl)
                        }
                    }
                } else {
                    mBinding.screenBack.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                        .into(mBinding.screenBack)
                }

            }

            CommonConst.DressUp.HOMEPAGE_BACKGROUND -> {
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.screenBack.visibility = View.VISIBLE
                Glide.with(mBinding.screenBack)
                    .load(ImageUtils.imgPath(item.displayUrl))
                    .into(mBinding.screenBack)
            }

            CommonConst.DressUp.PARTY_BACKGROUND -> {
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenBack.visibility = View.VISIBLE
                if (item.backpackId == BackpackFragment.DEFUSERBACKPACKDECORATION) {
                    Glide.with(mBinding.screenBack)
                        .load(drawable.default_party_bg)
                        .apply(RequestOptions().transform(CenterInside(), RoundedCorners(4.autoDp)))
                        .into(mBinding.screenBack)
                } else {
                    mBinding.previewLl.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack)
                        .load(ImageUtils.imgPath(item.displayUrl))
                        .apply(RequestOptions().transform(CenterInside(), RoundedCorners(4.autoDp)))
                        .into(mBinding.screenBack)
                }

            }

            CommonConst.DressUp.SOUND_EFFECT -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenPag.composition = PAGFile.Load("")

                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showScreenPag(effectDisplayUrl)
                        }
                    }
                } else {
                    mBinding.screenBack.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                        .into(mBinding.screenBack)
                }

            }

            CommonConst.DressUp.ROOM_FRAME -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenPag.composition = PAGFile.Load("")

                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showScreenPag(effectDisplayUrl)
                        }
                    }
                } else {
                    mBinding.screenBack.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                        .into(mBinding.screenBack)
                }

            }
        }
        if (item.received) {
            mBinding.detailsTv.visibility = View.VISIBLE
        } else {
            mBinding.detailsTv.visibility = View.GONE
        }
    }

    /**
     * 道具预览回调
     */
    override fun onBackPackSelectCallback(item: UserBackpackConsumableResp?) {
        mBinding.cosHead.visibility = View.GONE
        mBinding.avFv.visibility = View.GONE
        mBinding.cosProfile.visibility = View.GONE
        mBinding.chatIcon.visibility = View.GONE
        mBinding.cosScreen.visibility = View.GONE
        mBinding.frameAvatar.visibility = View.GONE
        mBinding.framePag.visibility = View.GONE
        mBinding.frameBack.visibility = View.GONE
        mBinding.screenPag.visibility = View.GONE
        mBinding.screenBack.visibility = View.GONE
        mBinding.effectIcon.visibility = View.GONE
        mBinding.profilePag.visibility = View.GONE
        mBinding.profileBack.visibility = View.GONE
        mBinding.previewLl.visibility = View.INVISIBLE
        mBinding.entryScreenItemview.visibility = View.GONE
        mLastItem = null
        if (item == null) {
            return
        }
        mBinding.cosScreen.visibility = View.VISIBLE
        mBinding.screenPag.composition = PAGFile.Load("")
        val effectDisplayUrl = item.effectDisplayUrl
        if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
            loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                    showScreenPag(effectDisplayUrl)
                }

            }
        } else {
            mBinding.screenBack.visibility = View.VISIBLE
            Glide.with(mBinding.screenBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
                .into(mBinding.screenBack)
        }
    }

    override fun goShopping(type: Long) {
        mOnBackPackSelectCallback?.goShopping(type)
    }

    override fun goBackpack(type: Long, childType: Int?) {
        var indexOf = -1
        mFragments.forEachIndexed { index, fragment ->
            when (fragment) {
                is BackpackFragment -> {
                    if (fragment.getType() == type) {
                        indexOf = index
                    }
                }

                is RoomBackgroundFragment -> {
                    if (fragment.getType() == type) {
                        fragment.tabChange(childType)
                        indexOf = index
                    }
                }

                is BackpackNumberFragment -> {
                    if (fragment.getType() == type) {
                        indexOf = index
                    }
                }

                is BackpackToolFragment -> {
                    if (fragment.getType() == type) {
                        indexOf = index
                    }
                }
            }
        }
        if (indexOf != -1) {
            mBinding.inContent.viewpager2.currentItem = indexOf
            mBinding.inContent.tab.onPageSelected(indexOf)
        }
    }

    //判断预览图是否为空
    private fun effectIsNull(effectDisplayUrl: String?, displayUrl: String): String {
        return if (effectDisplayUrl != null) {
            ImageUtils.imgPath(effectDisplayUrl)
        } else {
            ImageUtils.imgPath(displayUrl)
        }
    }

    //展示头像框 图片形式
    private fun showFrameImage(item: UserBackpackDecorationResp) {
        mBinding.cosHead.visibility = View.VISIBLE
        mBinding.frameAvatar.visibility = View.VISIBLE
        mBinding.frameBack.visibility = View.VISIBLE
        mBinding.frameAvatar.setImageUrl(UserManager.getUser().avatar)
        Glide.with(mBinding.frameBack).load(effectIsNull(item.effectDisplayUrl, item.displayUrl))
            .into(mBinding.frameBack)
    }

    //展示头像框 pag形式
    private fun showFramePag(item: UserBackpackDecorationResp) {
        mBinding.cosHead.visibility = View.VISIBLE
        mBinding.frameAvatar.visibility = View.VISIBLE
        mBinding.frameAvatar.setImageUrl(UserManager.getUser().avatar)
        val path =
            item.effectDisplayUrl?.let { FileUtils.getFilePath(FileUtils.getPagFile(), it) }
        mBinding.framePag.visibility = View.VISIBLE
        mBinding.framePag.apply {
            composition = PAGFile.Load(path)
            if (!isPlaying) {
                play()
            }
        }
    }

    //展示座驾pag
    private fun showScreenPag(effectDisplayUrl: String?) {
        val path = effectDisplayUrl?.let { FileUtils.getFilePath(FileUtils.getPagFile(), it) }
        mBinding.screenPag.visibility = View.VISIBLE
        mBinding.screenPag.apply {
            composition = PAGFile.Load(path)
            if (!isPlaying) {
                play()
            }
        }
        mBinding.screenPag.apply {
            composition = PAGFile.Load(path)
            setRepeatCount(1)
            if (!isPlaying) {
                play()
            }
        }
    }

    fun setOnBackPackCallback(l: BackPackSelectCallback) {
        mOnBackPackSelectCallback = l
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        withLoaded {
            if (hidden) {
                cancelTime()
            } else {
                if (isCreated()) {
                    startTime()
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        cancelTime()
    }

    //上次点击的item
    private var mLastUserBackpackNumberResp: UserBackpackNumberResp? = null

    override fun onBackPackSelectCallback(item: UserBackpackNumberResp?) {
        mBinding.cosHead.visibility = View.GONE
        mBinding.avFv.visibility = View.GONE
        mBinding.cosProfile.visibility = View.GONE
        mBinding.chatIcon.visibility = View.GONE
        mBinding.cosScreen.visibility = View.GONE
        mBinding.frameAvatar.visibility = View.GONE
        mBinding.framePag.visibility = View.GONE
        mBinding.frameBack.visibility = View.GONE
        mBinding.screenPag.visibility = View.GONE
        mBinding.screenBack.visibility = View.GONE
        mBinding.effectIcon.visibility = View.GONE
        mBinding.profilePag.visibility = View.GONE
        mBinding.profileBack.visibility = View.GONE
        mBinding.previewLl.visibility = View.INVISIBLE
        mBinding.entryScreenItemview.visibility = View.GONE
        mLastItem = null
        if (item == null) {
            return
        }
        mLastUserBackpackNumberResp = item
        mBinding.cosScreen.visibility = View.VISIBLE
        mBinding.screenPag.composition = PAGFile.Load("")
        val path = item.numberMedalPag
        if (path != null && path.endsWith(PagConst.PAG)) {
            loadPag(lifecycleScope, path) { pagPath, _ ->
                if (pagPath == mLastUserBackpackNumberResp?.numberMedalPag && !isDestroyView()) {
                    showScreenPag(path)
                }
            }
        } else {
            mBinding.screenBack.visibility = View.VISIBLE
            Glide.with(mBinding.screenBack).load(ImageUtils.imgPath(item.numberMedalPng))
                .into(mBinding.screenBack)
        }
    }
}